package com.drinks.yiniang.ui.widget.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.common.HotLineJson;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.conversation.ServiceChatActivity;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.utils.StringUtils;

import java.lang.reflect.Field;

/**
 * 客服 dialog
 *
 * Created by han on 2019/1/4 0004.
 */

public class ContactServiceDialog extends DialogFragment implements View.OnClickListener {

    private Dialog mDialog;

    //在线客服
    private ConstraintLayout csl_cs_online;
    //热线客服
    private ConstraintLayout csl_cs_hot_line;

    //热线时间
    private TextView tv_cs_time;
    private ProgressBar pbar_cs_hot_line;

    //热线号码
    private String mTelphone;

    public static ContactServiceDialog newInstance() {
        ContactServiceDialog mMaterialSingleDialog = new ContactServiceDialog();

        return mMaterialSingleDialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 定义Dialog布局和参数
        mDialog = new Dialog(getActivity(), R.style.MaterialDialogStyle);

        // 获取Dialog布局
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_contact_service, null);

        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);

        csl_cs_online = view.findViewById(R.id.csl_cs_online);
        csl_cs_hot_line = view.findViewById(R.id.csl_cs_hot_line);

        tv_cs_time = view.findViewById(R.id.tv_cs_time);

        pbar_cs_hot_line = view.findViewById(R.id.pbar_cs_hot_line);

        csl_cs_online.setOnClickListener(this);
        csl_cs_hot_line.setOnClickListener(this);

        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.CENTER; // 居中
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        getHotLineTime();

        return mDialog;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        Fragment mFragment = manager.findFragmentByTag(tag);
        //防止java.lang.IllegalStateException: Fragment already added
        if (mFragment == null || !mFragment.isAdded()) {
            //super.show(manager, tag);
            try {
                Field mDismissed = this.getClass().getSuperclass().getDeclaredField("mDismissed");
                Field mShownByMe = this.getClass().getSuperclass().getDeclaredField("mShownByMe");
                mDismissed.setAccessible(true);
                mShownByMe.setAccessible(true);
                mDismissed.setBoolean(this, false);
                mShownByMe.setBoolean(this, true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.csl_cs_online://在线客服
                dismiss();
                mIntent = new Intent(getActivity(), ServiceChatActivity.class);
                mIntent.putExtra(Constants.KeyBoolen, true);
                mIntent.putExtra(Constants.KeyTitle, getString(R.string.text_customer_service));
                startActivity(mIntent);
                break;
            case R.id.csl_cs_hot_line://热线客服
                if(StringUtils.isEmpty(mTelphone)) {
                    ToastUtils.showShort(R.string.text_no_hot_line);
                    return;
                }

                mIntent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + mTelphone);
                mIntent.setData(data);
                startActivity(mIntent);

                dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    @Override
    public void dismiss() {
        //super.dismiss();
        dismissAllowingStateLoss();
    }

    //获取热线时间段
    private void getHotLineTime() {
        pbar_cs_hot_line.setVisibility(View.VISIBLE);

        UserApiIO.getInstance().getTelephoneHotLineTime(new APIRequestCallback<HotLineJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(HotLineJson res) {
                mTelphone = res.getData().getTelephone();
                tv_cs_time.setText(getString(R.string.text_service_time) + " " + StringUtils.getNullEmptyConvert__(res.getData().getTime()));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {

            }

            @Override
            public void onComplete() {
                pbar_cs_hot_line.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
